/**
 * 系统后台多表夸库查询服务JS-SingleTableService.jsp
 */

var serviceOptions = {};
var operation = {};

var columnService1 = [];
var columnService2 = [];

var postPath = '/gdp'

$(function () {

    // 获取 url 参数
    location.href.replace(/([^?&=#]+)=([^?&=#]+)/g,function (str) {
        var param = str.split('=');
        operation[param[0]] = param[1];
    });

    // 绑定服务下拉列表
    $.getJSON(postPath + '/system/sysprjService/getPrjServiceData?order=asc&pageNo=1&pageSize=10&seachTxt=&pcode=&servertype=')
        .done(function (res) {
            if (res.success){
                var options = [];
                res.data.rows.map(function (data) {
                    // 优先支持单表服务和脚本服务
                    if (data.servicetype === 'executeSqlServer' || data.servicetype === 'singleTableServer' ) {
                        serviceOptions[data.servicecode] = data;
                        options.push({ label: data.servicename, value: data.servicecode });
                    }
                });

                $("#multSelect1").bindSelect({
                    max: 1,
                    placeholder: '请选择关联服务',
                    option:options,
                    onChange:function (res) {
                        columnService1 = [];
                        bindFileName(res,'#service_1',function (columnData,selected) {
                            columnService1 = columnData;
                            var serviceType = serviceOptions[res[0].value].servicetype;
                            $('#service1').val('{ "value": "' + res[0].value + '", "type": "'+ serviceType +'"}');
                            $('#service1_key').val(selected);
                        });
                    }
                });
    
                $("#multSelect2").bindSelect({
                    max: 1,
                    placeholder: '请选择关联服务',
                    option:options,
                    onChange:function (res) {
                        columnService2 = [];
                        bindFileName(res,'#service_2',function (columnData,selected) {
                            columnService2 = columnData;
                            var serviceType = serviceOptions[res[0].value].servicetype;
                            $('#service2').val('{ "value": "' + res[0].value + '", "type": "'+ serviceType +'"}');
                            $('#service2_key').val(selected);
                        });
                    }
                });

                operationFun();
            }
        })
        .error(function () {
            showMsg("获取数据源失败!", "error");
            // bootbox.alert("获取数据源失败!");
        });

    $("#btn_serverSave").on('click',function () {
        var data = {};
        $('#moreJoinForm').serializeArray().map(function (item) {
            data[item.name] = data[item.name] ? data[item.name] + ','+ item.value : item.value;
        });
        data['syscatch'] = data['sysCatch'];
        data['guid'] = data['guid'] ? data['guid'] : $('#guid_hiden').val();
        data['relatedServices'] = "[" + data['relatedServices'] + "]";
        var url = operation['operate'] === 'add' ? 'addMoreJoinService?servertype='+ operation['servertype'] +'&pCode='+ operation['projectid'] : 'updateMoreJoinService';


        if (formValidation(data)){
            $.ajax({
                method:'POST',
                url: postPath + '/system/morejoin/'+ url,
                data:JSON.stringify(data),
                dataType : 'json',
                contentType:"application/json",
            }).done(function (res) {
                if (res === 1){
                    operation['operate'] = 'edit';
                    $('#guid').attr('disabled',true);
                    // bootbox.alert("保存查询服务成功!");
                    showMsg("保存成功!", "success");
                }else if (res === 2){
                    // bootbox.alert("服务ID 已存在!");
                    showMsg("服务ID已存在!", "error");
                }
            });
        }
    });


    $("#a_tab_column").on('click',function(){
        var column =  _concat(columnService1,columnService2);
        if (operation['operate'] === 'add'){
            // bootbox.alert("请选择服务!");
            showMsg("请选择服务!", "warning");
            return false;
        }

        $("#tb_fieldList")
            .bootstrapTable('destroy')
            .bootstrapTable({
                data: column,
                columns : [ {
                    title : '字段名称',
                    field : 'filedname',
                    align : 'center',
                    valign : 'middle'
                },{
                    title : '中文名称',
                    field : 'fieldcaption',
                    align : 'center',
                    valign : 'middle'
                }]
            });

    });
});

// 获取 数据列表字段名 url
var getServerColumnURL = function (serviceType) {
    switch (serviceType) {
        case "executeSqlServer":
            return postPath + "/system/server/selectServerColumn?order=asc&sysId=";
        case "singleTableServer":
            return postPath + "/system/showfield/getShowFieldList?serviceType=1&serviceId=";
        default:
            return "";
    }
}


// 绑定数据列
var bindFileName = function (res, ele, func) {
    if (res.length > 0){
        var columnUrl = getServerColumnURL(serviceOptions[res[0].value].servicetype);
        if (columnUrl !== ''){
            $.getJSON(columnUrl+ res[0].value)
                .done(function(data){
                    $(ele).html('');
                    for (var i = 0; i < data.length; i++) {

                        var fileName = data[i].filedname || data[i].fieldname;
                        var filedNameCn = data[i].fieldcaption || data[i].fieldnameCn;

                        $(ele).append('<li class="list-group-item" data-value="'+ fileName +'">'+  fileName +'(' + filedNameCn + ')</li>');
                    }

                    var selectedFileName = '';
                    $(ele + ' li').on('click',function () {
                        $(ele + ' li i').remove();
                        $(this).append('<i class="fa fa-check pull-right" aria-hidden="true"></i>');
                        selectedFileName = $(this).data('value');
                        if (func){ func(data,selectedFileName);}
                    });

                    if (func){ func(data,selectedFileName);}
                })
                .error(function () {
                    // bootbox.alert("获取数据源失败!");
                    showMsg("获取数据源失败!", "error");
                });
        }
    }else {
        $(ele).html('');
    }
}

var operationFun = function () {
    // 如果 operate 不等于 add，则禁止 服务ID 输入
    if (operation['operate'] != 'add'){
        $('#guid').attr('disabled',true);
    }

    // 设置缓存时间是否禁用
    $('input[name="sysCatch"]').on('change',function () {
       var readonly =  $(this).attr('value') == 0 ? true : false;
       $('#catchtime').attr('readonly', readonly);
    });


    // 编辑数据绑定数据值
    if (operation['servercode']){
        $.getJSON(postPath + '/system/morejoin/getMoreJoinService?servercode='+ operation['servercode'])
            .done(function (res) {
                $('#serviceName').val(res.serviceName);
                $('#guid').val(res.guid);
                $('#guid_hiden').val(res.guid);
                $('input[name="sysCatch"][value="'+ res.syscatch +'"]').prop('checked',true);
                if (res.syscatch == 1){
                    $('#catchtime').attr('readonly', false);
                }

                $('#catchtime').val(res.catchtime);
                $('input[name="ispagination"][value="'+ res.ispagination +'"]').prop('checked',true);

                var relatedServices = JSON.parse(res.relatedServices)
                $('#service1').val(relatedServices[0].value);
                $('#service2').val(relatedServices[1].value);
                $("#multSelect1").setSelectValue(relatedServices[0].value);
                $("#multSelect2").setSelectValue(relatedServices[1].value);

                var relatedKey =  res.relatedKey.split(',');
                $('#service1_key').val(relatedKey[0]);
                $('#service2_key').val(relatedKey[1]);

                setTimeout(function () {
                    $('#service_1 li[data-value="'+ relatedKey[0] +'"]').click();
                    $('#service_2 li[data-value="'+ relatedKey[1] +'"]').click();
                },500);
            })
            .error(function () {
                showMsg("获取数据源失败!", "error");
                // bootbox.alert("获取数据源失败!");
            });
    }
}

// 表达验证
var formValidation = function (data) {
    if ($.trim(data['serviceName']) === '') {
        $("#valide_dtMessage").text("服务名称不能为空!");
        return false
    } else if ($.trim(data['guid']) === ''){
        $("#valide_dtMessage").text("服务ID不能为空!");
        return false
    }else if ($.trim($('#service1').val()) === '' || $.trim($('#service2').val()) === ''){
        $("#valide_dtMessage").text("请选择服务!");
        return false
    }else if ($.trim($('#service1_key').val()) === '' || $.trim($('#service2_key').val()) === ''){
        $("#valide_dtMessage").text("请选择服务关联列名!");
        return false
    }else if (data['sysCatch'] == 1 && $.trim(data['catchtime']) === '') {
        $("#valide_dtMessage").text("缓存时间不能为空!");
        return false
    }
    $("#valide_dtMessage").text("");
    return true;
}

// 合并两个数组，并去重
var _concat = function(arr1,arr2){
    var arr = [];
    var record = [];
    for (var i = 0; i < arr1.length ; i++) {
        var fileName = arr1[i].filedname || arr1[i].fieldname;
        var filedNameCn = arr1[i].fieldcaption || arr1[i].fieldnameCn;
        arr.push({ filedname: fileName, fieldcaption : filedNameCn });
        record.push(fileName);
    }
    for(var i = 0;i< arr2.length;i++){
        var fileName = arr2[i].filedname || arr2[i].fieldname;
        var filedNameCn = arr2[i].fieldcaption || arr2[i].fieldnameCn;
        var obj = { filedname: fileName, fieldcaption : filedNameCn }

        if (record.indexOf(fileName) === -1){
            arr.push(obj)
        }
    }
    return arr;
}
function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}
